<template>
  <div class="login-container">
    <!-- 带本地图标的系统标题 -->
    <h1 class="system-title">
      <img src="../../../public/pile.png" alt="充电桩图标" class="title-icon" />
      新能源汽车充电桩智能管理系统
    </h1>
    <div class="main-content">
      <!-- 左侧插画（无蓝边优化） -->
      <div class="illustration">
        <img src="../../../public/login_index.png" alt="新能源汽车充电插画" class="full-image" />
      </div>

      <!-- 右侧登录/注册表单容器 -->
      <div class="form-panel">
        <!-- 登录表单 -->
        <el-form v-if="isLogin" ref="loginForm" :model="loginForm" :rules="loginRules" class="auth-form">
          <h3 class="form-title">系统登录</h3>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入账号" prefix-icon="el-icon-user"
              class="input-with-shadow" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="el-icon-lock"
              class="input-with-shadow" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%;" @click="handleLogin" class="gradient-btn">
              点击登录
            </el-button>
          </el-form-item>
          <div class="form-footer">
            没有账号？
            <el-button type="text" @click="toggleForm" class="link-btn">
              去注册
            </el-button>
          </div>
        </el-form>

        <!-- 注册表单 -->
        <el-form v-else ref="registerForm" :model="registerForm" :rules="registerRules" class="auth-form">
          <h3 class="form-title">系统注册</h3>
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入账号" prefix-icon="el-icon-user"
              class="input-with-shadow" />
          </el-form-item>
          <el-form-item prop="phone"> <!-- 新增手机号字段 -->
            <el-input v-model="registerForm.phone" placeholder="请输入手机号" prefix-icon="el-icon-phone"
              class="input-with-shadow" />
          </el-form-item>
          <el-form-item prop="realName"> <!-- 新增真实姓名字段 -->
            <el-input v-model="registerForm.realName" placeholder="请输入真实姓名" prefix-icon="el-icon-user-solid"
              class="input-with-shadow" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="请输入密码（至少6位）"
              prefix-icon="el-icon-lock" class="input-with-shadow" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%;" @click="handleRegister" class="gradient-btn">
              点击注册
            </el-button>
          </el-form-item>
          <div class="form-footer">
            已有账号？
            <el-button type="text" @click="toggleForm" class="link-btn">
              去登录
            </el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'  // 引入request工具
import { setToken } from '@/utils/auth'  // 引入token工具
export default {
  name: 'AuthPage',
  data() {
    return {
      isLogin: true, // 控制登录/注册切换
      // 登录表单数据
      loginForm: {
        username: '',
        password: '',
        identity: '' // 身份：user/admin
      },
      // 注册表单数据
      registerForm: {
        username: '',
        password: '',
        phone: '', // 新增手机号
        realName: '' // 新增真实姓名
      },
      // 登录表单验证规则
      loginRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 4, max: 20, message: '账号长度为4-20位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ]

      },
      registerRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 4, max: 20, message: '账号长度为4-20位', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '姓名长度为2-10位', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    // 切换登录/注册表单
    toggleForm() {
      this.isLogin = !this.isLogin;
      // 重置表单
      this.$nextTick(() => {
        if (this.isLogin) {
          this.$refs.registerForm?.resetFields();
        } else {
          this.$refs.loginForm?.resetFields();
        }
      });
    },
    // 登录提交
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            const loading = this.$loading({ lock: true, text: '登录中...', spinner: 'el-icon-loading' })

            const response = await request({
              url: '/user/login',
              method: 'post',
              data: this.loginForm
            })

            // 处理登录结果
            console.log(response)
            setToken(response.data.token)
            localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo))
            localStorage.setItem('token',response.data.token)
            this.$store.commit('user/SET_TOKEN', response.data.token)
            this.$message.success('登录成功！')

            const redirectPath = this.$route.query.redirect || '/dashboard'
            loading.close()
            this.$nextTick(() => {
              this.$router.push(redirectPath).catch(err => {
                // 捕获路由跳转可能的错误（如重复跳转同一路径）
                console.warn('路由跳转警告:', err)
              })
            })

          } catch (error) {
            // this.$message.error(error.response?.data?.message || '登录失败，请检查账号密码')
            this.$loading().close()
          }
        }
      })
    },

    // 注册提交
    handleRegister() {
      this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          try {
            const loading = this.$loading({ lock: true, text: '注册中...', spinner: 'el-icon-loading' })

            // 直接调用注册接口
            await request({
              url: '/user/register',
              method: 'post',
              data: this.registerForm
            })

            this.$message.success('注册成功，请登录！')
            this.toggleForm()
            this.loginForm.username = this.registerForm.username
            loading.close()
          } catch (error) {
            // this.$message.error(error.response?.data?.message || '注册失败，请稍后重试')
            this.$loading().close()
          }
        }
      })
    }
  }
};
</script>

<style scoped lang="scss">
/* 系统标题样式 */
/* 本地图标样式（替换原有 title-icon 样式） */
.title-icon {
  width: 24px;
  /* 图标宽度，与文字大小匹配 */
  height: 24px;
  /* 图标高度，保持正方形 */
  margin-right: 8px;
  /* 与文字间距 */
  vertical-align: middle;
  /* 垂直居中对齐 */
  object-fit: contain;
  /* 保持图标比例，不拉伸 */
}

/* 保留原有标题布局样式 */
.system-title {
  position: absolute;
  top: 30px;
  left: 40px;
  color: #1a73e8;
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  padding: 0;
  letter-spacing: 0.5px;
  z-index: 10;
  display: flex;
  align-items: center;
  /* 确保图标和文字垂直居中 */
}

/* 响应式适配不变 */
@media (max-width: 768px) {
  .system-title {
    font-size: 16px;
    top: 20px;
    left: 20px;
  }

  .title-icon {
    width: 20px;
    height: 20px;
  }
}

/* 全局容器样式 */
.login-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

/* 主内容区（插画+表单） */
.main-content {
  width: 100%;
  max-width: 1200px;
  height: 600px;
  display: flex;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  /* 隐藏溢出内容，避免圆角外显示 */
}

/* 左侧插画容器（无蓝边核心样式） */
.illustration {
  flex: 1;
  height: 100%;
  position: relative;
  /* 相对定位用于图片绝对定位 */
  margin: 0;
  /* 清除默认外边距 */
  padding: 0;
  /* 清除默认内边距 */
  background: transparent;
  /* 确保无背景色干扰 */
}

/* 图片全屏显示（无蓝边关键） */
.full-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* 覆盖容器且不变形 */
  object-position: center;
  /* 居中裁剪 */
  display: block;
  /* 清除图片底部间隙 */
}

/* 右侧表单面板 */
.form-panel {
  flex: 0 0 400px;
  /* 固定宽度400px */
  padding: 60px 40px;
  background: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

/* 表单样式 */
.auth-form {
  width: 100%;
}

.form-title {
  text-align: center;
  color: #1a73e8;
  font-size: 24px;
  margin-bottom: 30px;
  font-weight: 600;
}

/* 带阴影的输入框 */
.input-with-shadow {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  border: 1px solid #e8e8e8;
  transition: all 0.3s;

  &:focus-within {
    border-color: #1a73e8;
    box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.1);
  }
}

/* 渐变按钮 */
.gradient-btn {
  background: linear-gradient(90deg, #1a73e8, #0d47a1);
  border: none;
  height: 48px;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s;

  &:hover {
    background: linear-gradient(90deg, #0d47a1, #1565c0);
    transform: translateY(-2px);
  }
}

/* 底部链接 */
.form-footer {
  text-align: center;
  margin-top: 20px;
  color: #666;
  font-size: 14px;
}

.link-btn {
  color: #1a73e8 !important;
  padding: 0 5px;
}
</style>
